package org.jground.rx.ui.zk;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;
import org.jground.rx.IRXObjectSynopsis;
import org.jground.rx.RXObjectService;
import org.jground.rx.RXSearchCriteria;
import org.jground.rx.ui.IMainPanel;
import org.jground.rx.ui.IUISearchPanel;
import org.jground.util.L;
import org.jground.zk.zulX.DivX;
import org.jground.zk.zulX.HboxX;
import org.jground.zk.zulX.PanelX;
import org.jground.zk.zulX.WindowX;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Hbox;

public class UISearchWindow extends WindowX implements EventListener, IMainPanel<Component> {
    //
    // CLASS LEVEL
    //
    private static Log logger = LogFactory.getLog(UISearchWindow.class);
    public static int PAGING_SIZE = 20;
    private static String defaultSearchResultTitle = "Search Result (none)";
    //
    // OBJECT LEVEL
    //
    private UIFrame uiFrame;
    // 
    // Search Criteria Widgets
    //
    // private Textbox queryTB;
    // private List<Checkbox> moClassIncludeCBs;
    // private Checkbox includeDeletedCB;
    // private List<Checkbox> topLevelCBs = new ArrayList<Checkbox>(4);
    // private Checkbox restrictToBeApprovedCB;
    // private Checkbox includeAllCB;
    //
    private Button searchBt;
    private Button resetBt;
    //
    private DivX searchCriteriaePanel;
    private UIResultList resultList;
    private PanelX resultPanel;
    private HboxX resultWindowHbox;
    // 
    // private int numberOfSelctionMoids;
    private RXSearchCriteria currentSC;

    private IUISearchPanel<Component> searchPanel;

    public UISearchWindow(UIFrame uiFrame) {
        logger.debug("start init");
        this.uiFrame = uiFrame;
        // this.setTitle("Search");
        // this.setBorder("normal");
        // this.setClosable(true);
        this.setTitle("");
        this.setBorder("none");
        this.setClosable(false);
        //
        // CREATE
        //
        searchCriteriaePanel = new DivX();
        //searchCriteriaePanel.setBorder("normal");
        searchCriteriaePanel.setWidth("100%");
        searchCriteriaePanel.setStyle("border:red 0px dotted");
        
        //
        // moClassIncludeCBs = new ArrayList<Checkbox>();
        // ArrayList<String> moids = new ArrayList<String>();
        // for (RXClass moc : RXSystem.getInstance().getRxService().getAllRXClasses()) {
        // moids.add(moc.getMoid());
        // }
        //
        // Vbox moidSelection = new Vbox();
        // numberOfSelctionMoids = createMoidSelection(moidSelection,
        // UIHelper.filterReadableTopLevelMoids(moids),
        // moClassIncludeCBs, "S");
        //
        // queryTB = new Textbox();
        // queryTB.setWidth("200px");
        // //
        // //
        // includeDeletedCB = new Checkbox();
        // restrictToBeApprovedCB = new Checkbox();
        // includeAllCB = new Checkbox();
        //
        searchBt = new Button("Search");
        resetBt = new Button("Reset");
        
        //
        // resultLabel = new Label();
        // resultLabel.setStyle("padding: 4px;margin: 4px");
        //
        resultList = new UIResultList(uiFrame);
        resultList.setPageSize(PAGING_SIZE);
        resultList.setWidth("100%");
        resultWindowHbox = new HboxX();
        resultWindowHbox.setStyle("padding: 4px");
        resultWindowHbox.setWidth("100%");
        resultPanel = new PanelX("Result Window", "normal", true);
        resultPanel.setStyle("margin-top: 4px");
        resultPanel.setWidth("100%");
        //
        // LAYOUT
        //

        // GRID for search criteria

        // GridX grid = new GridX("*", "*");
        // //
        //
        // // SEARCH TEXT
        // grid.addAsRow(new Label("Search Text"), queryTB);
        // //
        // if (numberOfSelctionMoids > 1) {
        // // INCLUDE ALL
        // grid.addAsRow(new Label("Include All"), includeAllCB);
        // // SELECTION
        // grid.addAsRow(new Label(" "), moidSelection);
        // } else {
        // logger.info("number of MOID to select is less then 2. So we don't show any selection for search!");
        // }
        // INCLUDE DELETED
        // if (RXAccess.getInstance().isSysadmin()) {
        // grid.addAsRow(new Label("Include Deleted"), includeDeletedCB);
        // }
        // TO BE APPROVED
        // grid.addAsRow(new Label("To Be Approved"), restrictToBeApprovedCB);
        searchPanel = new UISearchPanelSimple(uiFrame);

        // searchSimplePanel.setStyle("padding: 4px");
        searchCriteriaePanel.add(searchPanel.getView());
        // BUTTONS
        Hbox buttonBX = null;
        searchCriteriaePanel.add(buttonBX = new Hbox());
        // hbox.setStyle("padding: 4px");
        buttonBX.setSclass(UIStyles.BUTTONGROUP);
        searchBt.setParent(buttonBX);
        resetBt.setParent(buttonBX);
        //
        set(searchCriteriaePanel);
        //
        // this.add(resultPanel);
        // resultPanel.add(resultLabel);
        resultPanel.add(resultWindowHbox);

        //
        // EVENTS
        //
        // includeAllCB.addEventListener(Events.ON_CHECK, this);
        searchBt.addEventListener(Events.ON_CLICK, this);
        resetBt.addEventListener(Events.ON_CLICK, this);
        this.addForward(Events.ON_OK, searchBt, Events.ON_CLICK);
    }

    // private int createMoidSelection(Vbox vbox, List<String> moids,
    // List<Checkbox> cbList, String style) {
    // int counter = 0;
    // for (String moid : moids) {
    // RXClass moc = RXSystem.getInstance().getRxService().getRXClass(moid);
    // if (moc == null) {
    // continue;
    // }
    // if (RXAccess.getInstance().canRead(moc)) {
    // Checkbox cb = new Checkbox();
    // String name = moc.getName();
    // cb.setLabel(name);
    // cb.setParent(vbox);
    // cbList.add(cb);
    // cb.setAttribute("moid", moid);
    // topLevelCBs.add(cb);
    // counter++;
    // }
    // }
    // return counter;
    // }

    public void onEvent(Event e) throws Exception {
        if (e.getTarget() == searchBt) {
            // if (numberOfSelctionMoids == 1) {
            // this.includeAllCB.setChecked(true);
            // }
            // Messagebox.show("Search Button Clicked");
            // doSearch(createSearchCriteriaFromGUI());
            doSearch(searchPanel.getSearchCriteria());
        }
        if (e.getTarget() == resetBt) {
            // Messagebox.show("Reset Button Clicked");
            if (resultList != null) {
                resultList.removeAllObject();
            }
            // queryTB.setValue("");
            // includeAllCB.setChecked(false);
            // includeDeletedCB.setChecked(false);
            // restrictToBeApprovedCB.setChecked(false);
            // for (Checkbox cb : topLevelCBs) {
            // cb.setChecked(false);
            // cb.setDisabled(false);
            // }
            searchPanel.reset();
            // resultLabel.setValue("");
            resultPanel.setTitle(defaultSearchResultTitle);
            currentSC = null;
            set(searchCriteriaePanel);
        }
        // if (e.getTarget() == includeAllCB) {
        // for (Checkbox cv : topLevelCBs) {
        // cv.setDisabled(includeAllCB.isChecked());
        // }
        // }
    }

    public void doSearch() {
        if (currentSC != null) {
            logger.debug(currentSC);
            List<IRXObjectSynopsis> rxSynopsisList = RXObjectService.getInstance().search(currentSC);
            L.debug(logger, "result list ", rxSynopsisList.size());
            // resultLabel.setValue("Found " + result.size() + " elements.");
            // if (currentResultList != null) {
            // currentResultList.detach();
            // }
            // currentResultList = new UIResultList(uiFrame, result);
            // currentResultList.setParent(resultVbox);
            resultList.removeAllObject();
            resultWindowHbox.removeAll();
            if (CollectionUtils.isNotEmpty(rxSynopsisList)) {
                resultPanel.setTitle("Search Result :: found " + rxSynopsisList.size() + " element"
                        + (rxSynopsisList.size() > 1 ? "s" : ""));
                resultList.addObjects(rxSynopsisList);
                //resultList.invalidate();
                resultWindowHbox.set(resultList);
                resultWindowHbox.invalidate();
                this.set(searchCriteriaePanel, resultPanel);
            } else {
                resultPanel.setTitle(defaultSearchResultTitle);
                UIMessageboxUtils
                        .showInfoMessage("Sorry, no results found. Please, try to change the search criteria.");
            }
            resultPanel.setHeight(null);
            resultWindowHbox.setHeight(null);
        } else {
            logger.warn("no search critera object!");
        }

    }

    public void doSearch(RXSearchCriteria searchCriteria) {
        currentSC = searchCriteria;
        doSearch();
    }

    // private RXSearchCriteria createSearchCriteriaFromGUI() {
    // RXSearchCriteria sc = new RXSearchCriteria();
    // //
    // String searchString = this.queryTB.getValue();
    // sc.setSearchString(searchString);
    // logger.debug("query: " + queryTB.getValue());
    // // MODataStates defaults
    // sc.addIncludedDataStates(RXDataState.APPROVED, RXDataState.STORED);
    // //
    // if (includeDeletedCB.isChecked()) {
    // sc.addIncludedDataStates(RXDataState.DELETED,
    // RXDataState.DELETED_UNAPPROVED);
    // }
    // if (restrictToBeApprovedCB.isChecked()) {
    // sc.setIncludedDataStates(RXDataState.DELETED_UNAPPROVED,
    // RXDataState.STORED);
    // includeDeletedCB.setChecked(false);
    // }
    // for (Checkbox cb : topLevelCBs) {
    // String moid = (String) cb.getAttribute("moid");
    // if (cb.isChecked() || includeAllCB.isChecked()) {
    // sc.addIncludedMoids(moid);
    // }
    // }
    // return sc;
    // }

    public void refreshSearch() {
        if (currentSC != null) {
            doSearch();
        }
    }

    public void beforeClose() {}

    public void beforeShow() {
        refreshSearch();
    }

    public Component getView() {
        return this;
    }

    public UIFrame getUiFrame() {
        return uiFrame;
    }

}